<template>
    <view class="container-qcode" :style="{ background: easyGetColor('red') }">
        <header-bar :config="config"></header-bar>
        <image class="bg" :src="bg" mode="aspectFill"></image>
        <!-- "crossOrigin",'Anonymous' -->
        <!-- @longpress="canvas.save" -->
        <view class="qcode-box" id="myCanvas">
            <image class="qcode-bg" :src="imageBg" mode="aspectFill"></image>
            <view class="order-info">
                <view class="title">待支付金额(元)</view>
                <view class="price">¥{{ money }}</view>
                <view class="no">订单号：{{ Sn }}</view>
            </view>
            <text class="qcode-text">请用{{ name }}扫码付款</text>
            <image v-if="url_base64" :src="imageSrc" class="qcode-img" @longpress="canvas.save"></image>
            <image v-else :src="qcode" mode="" class="qcode-img" @longpress="save"></image>
        </view>
        <view class="longpress-text">长按保存二维码</view>
    </view>
</template>

<script>
import { pathToBase64, base64ToPath } from 'image-tools'
import config from "@/config/config.js"
export default {
    components: {},
    props: {
        name: {
            type: String,
            default: "微信",
        },
        qcode: {
            type: String,
            default: "",
        },
        url_base64: {
            type: String,
            default: "",
        },
        Sn: {
            type: String,
            default: "",
        },
        money: {
            type: [String, Number],
            default: "",
        },
    },
    data() {
        return {
            config: {
                title: "收款二维码",
                color: "#ffffff",
                isCustomBackFn: true,
            },
            bg: "/static/qcode/bg.png",
            qcodeBg: 'static/qcode/box.png',
            errortip: "",
            tempFilePath: "",
            imageBg: "",
            // imageSrc: "",
        }
    },
    created() {
        let mainColor = this.easyGetColor("red")
        this.config.backgroundColor = [1, mainColor]
        // this.imageSrc = "data:image/png;base64," + this.url_base64.replace(/[\r\n]/g, "");
    },
    onLoad(e) {
        const query = uni.createSelectorQuery().in(this);
        query.select('#yourImageId').fields({ node: true, computeStyle: true }).exec(res => {
            if (res[0].node) {
                res[0].node.crossOrigin = "anonymous"; // 注意：这里实际上是无效的，因为uni-app的API不直接支持这样设置，但你可以通过其他方式间接实现。
            }
        });
    },
    mounted() {
        // const path = require('path');
        // let imagePath = path.join(path.dirname(__dirname), 'static/qcode/box.png');
        if (typeof window === 'object' && 'document' in window) {
            this.qcodeBg = require('@/static/qcode/box.png')
        }
        pathToBase64(this.qcodeBg).then(res => {
            console.log("res", res)
            this.imageBg = res
        }).catch(error => {
            console.error(error)
        })
    },
    computed: {
        imageSrc() {
            return "data:image/png;base64," + this.url_base64.replace(/[\r\n]/g, "");
        }
    },
    methods: {
        changeName(url, newFileName) {
            return new Promise(resolve => {
                plus.io.resolveLocalFileSystemURL(url, entry => {
                    entry.getParent(_oldFile => {
                        entry.moveTo(_oldFile, '/' + newFileName, newFilePath => {
                            resolve(newFilePath.fullPath);
                        }, (err) => {
                            console.error("文件移动失败", err);
                            reject(`文件移动失败: ${err.message}`);
                        }
                        );
                    });
                });
            });
        },
        checkPhotoPermission() {
            return new Promise((resolve, reject) => {
                console.log("checkPhotoPermission")
                uni.getSetting({
                    success(res) {
                        console.log("checkPhotoPermission", res)
                        if (!res.authSetting['scope.writePhotosAlbum']) {
                            uni.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success() {
                                    console.log("授权成功");
                                    resolve(true);
                                },
                                fail() {
                                    reject(new Error('用户拒绝相册权限'));
                                }
                            });
                        } else {
                            resolve(true);
                        }
                    },
                    fail() {
                        console.log("checkPhotoPermission获取权限失败")
                        reject(new Error('获取权限失败'));
                    }
                });
            });
        },
        save(e) {
            console.log("save", this.qcode)
            //#ifdef APP-PLUS
            if (this.qcode.indexOf('https://') == -1) {
                this.saveBase64Img(this.qcode)
            } else {
                const imageSrc = e.currentTarget.src; // 获取图片链接
                uni.downloadFile({
                    url: this.qcode,
                    success: async downloadResult => {
                        if (downloadResult.statusCode === 200) {
                            console.log('下载成功', downloadResult.tempFilePath)
                            let name = "_doc/" + new Date() + ".png";
                            // 重命名的方法
                            // await this.checkPhotoPermission(); // 先检查权限
                            let tempFilePath = await this.changeName(downloadResult.tempFilePath, name);
                            uni.saveImageToPhotosAlbum({
                                filePath: tempFilePath,
                                success: () => {
                                    console.log('保存成功')
                                    uni.showToast({ title: '保存成功' });
                                },
                                fail: (err) => {
                                    console.log('保存失败', err)
                                    uni.showToast({ title: '保存失败', icon: 'none' });
                                }
                            });
                        }
                    },
                    fail: () => {
                        uni.showToast({ title: '下载失败', icon: 'none' });
                    }
                });
            }
            // #endif
        },
        saveBase64Img(base64) {
            let _this = this
            const bitmap = new plus.nativeObj.Bitmap("test")
            bitmap.loadBase64Data(
                base64,
                function () {
                    const url = "_doc/" + new Date() + ".png" // url建议用时间戳命名方式
                    console.log("url:", url)
                    bitmap.save(
                        url,
                        {
                            overwrite: true, // 是否覆盖
                            // quality: 'quality'  // 图片清晰度
                        },
                        (i) => {
                            uni.saveImageToPhotosAlbum({
                                filePath: url,
                                success: function () {
                                    console.log("保存成功")
                                    _this.easyToast("保存成功，请到手机相册")
                                    _this.teamShare = null
                                    bitmap.clear()
                                },
                            })
                        },
                        (e) => {
                            console.log("保存失败", e)
                            _this.easyToast(e)
                            bitmap.clear()
                        },
                    )
                },
                (e) => {
                    console.log("保存失败", e)
                    bitmap.clear()
                },
            )
        },
        // 获取生成的base64 图片路径
        receiveRenderData(val) {
            var posterUrl = val.replace(/[]/g, ''); // 去除base64位中的空格
            this.saveBase64Img(posterUrl)
        },
    },
}
</script>
<script module="canvas" lang="renderjs">
    import html2canvas from 'html2canvas'
	export default {
		mounted() {},
		methods: {
            save(e) {
                try {
                    const timeout = setTimeout(async () => {
                        const dom = document.getElementById('myCanvas') // 获取包含需要保存为图片的元素的容器
                        html2canvas(dom, {
                            width: dom.clientWidth, //dom 原始宽度
                            height: dom.clientHeight,
                            scrollY: 0, // html2canvas默认绘制视图内的页面，需要把scrollY，scrollX设置为0
                            scrollX: 0,
                            allowTaint: true,
                            useCORS: true, //支持跨域
                            // scale: 2, // 设置生成图片的像素比例，默认是1，如果生成的图片模糊的话可以开启该配置项
                        }).then((canvas) => {
                            // 生成成功
                            console.log("生成成功")
                            // html2canvas 生成成功的图片链接需要转成 base64位的url
                            this.$ownerInstance.callMethod('receiveRenderData', canvas.toDataURL('image/png'))
                        }).catch(err=>{
                            console.log("生成图片失败" + err);
                        })
                    }, 500);
                } catch (e) {
                    console.log(e);
                }                
            }
        },
	}
</script>

<style lang="scss">
.container-qcode {
    // background: $app-color-main;
    position: relative;
    height: 100vh;

    .bg {
        position: absolute;
        width: 100%;
        height: 100%;
    }

    .qcode-box {
        position: relative;
        width: calc(100% - 96rpx);
        margin: 200rpx 48rpx 20rpx;
        height: 0;
        box-sizing: border-box;
        padding: 0 0 0 0;
        padding-top: calc(125% - 120rpx);

        .qcode-bg {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
        }

        .order-info {
            position: absolute;
            font-size: 30rpx;
            top: 120rpx;
            left: calc(50% - 218rpx);

            .title {
                font-size: 28rpx;
            }

            .price {
                font-size: 36rpx;
                font-weight: bold;
                padding: 6rpx 0;
            }

            .no {
                font-size: 24rpx;
            }
        }

        .qcode-text {
            position: absolute;
            width: 100%;
            text-align: center;
            color: $color-white;
            font-size: 30rpx;
            top: 38rpx;
        }

        .qcode-img {
            height: 436rpx;
            width: 436rpx;
            left: calc(50% - 218rpx);
            position: absolute;
            bottom: 10%;
            border-radius: 16px;
            border: 2px solid #F1270C;
        }
    }

    .longpress-text {
        color: $color-white;
        text-align: center;
        position: relative;
        z-index: 2;
    }
}
</style>
